﻿var viewModel = function (data) {
    this.pageSize = ko.observable(data.PgIndex);
    this.currentPage = ko.observable(data.PageNumber);
    this.pageData = ko.observableArray(ko.mapping.fromJS(data.Data));
    this.recordCount = ko.observable(data.RecordCount);
    this.sortType = "ascending";
    this.currentColumn = ko.observable("");
    this.iconType = ko.observable("");
    this.currentPageIndex = ko.observable(0);
    this.maxPageIndex = ko.observable(Math.ceil(data.RecordCount / data.PageSize) - 1);
    var Pager = (this.maxPageIndex() + 1 >= 10) ? 10 : this.maxPageIndex() + 1;
    this.pager = ko.observable(Pager);
    this.isLastPage = function () {
        var recordsLeft = (this.recordCount() - (this.pageSize() * this.currentPage()))
        return recordsLeft <= 0;
    }
    this.isFirstPage = function () {
        return this.currentPage() == 1;
    }
    this.sortTable = function (viewModel, e) {
        var orderProp = $(e.target).attr("data-column")
        viewModel.currentColumn(orderProp);
        viewModel.pageData.sort(function (a, b) {
            var valueA = a[orderProp]._latestValue;
            var valueB = b[orderProp]._latestValue;
            if (typeof valueA != "number" && typeof valueA != "object") {
                valueA = valueA.toString().toLowerCase();
                valueB = valueB.toString().toLowerCase();
            }
            if (this.vm.sortType == "ascending") {
                return valueA < valueB ? -1 : 1;
            }
            else {
                return valueA > valueB ? -1 : 1;
            }
        });
        viewModel.sortType = (viewModel.sortType == "ascending") ? "descending" : "ascending";
        viewModel.iconType((viewModel.sortType == "ascending") ? "sorting_desc" : "sorting_asc");
    };
}
